package com.vue.admin.service.common.mybatis.provider;

import org.apache.ibatis.mapping.MappedStatement;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

import java.util.Iterator;
import java.util.Set;

import static tk.mybatis.mapper.mapperhelper.SqlHelper.whereVersion;

/**
 * @program: tk-robot-service
 * @description: 批量更新
 * @author: zhangyangyang
 * @create: 2020-01-07 10:03
 **/
public class BaseDefUpdateProvider extends MapperTemplate {
    public BaseDefUpdateProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

    public String updateListByPrimaryKeySelective(MappedStatement ms) {
        Class<?> entityClass = this.getEntityClass(ms);
        StringBuilder sql = new StringBuilder();
        sql.append("<foreach collection=\"list\"  separator=\";\"  item=\"item\">");
        sql.append(SqlHelper.updateTable(entityClass, this.tableName(entityClass)));
        sql.append(SqlHelper.updateSetColumns(entityClass, "item", true, this.isNotEmpty()));
        sql.append(wherePKColumns(entityClass, true));
        sql.append("</foreach>");
        return sql.toString();
    }

    public static String wherePKColumns(Class<?> entityClass, boolean useVersion) {
        StringBuilder sql = new StringBuilder();
        sql.append("<where>");
        Set<EntityColumn> columnSet = EntityHelper.getPKColumns(entityClass);
        Iterator var4 = columnSet.iterator();

        while(var4.hasNext()) {
            EntityColumn column = (EntityColumn)var4.next();
            sql.append(" AND " + column.getColumnEqualsHolder("item"));
        }

        if (useVersion) {
            sql.append(whereVersion(entityClass));
        }

        sql.append("</where>");
        return sql.toString();
    }
}
